package com.moon.game.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import com.google.gson.Gson;
import com.google.protobuf.GeneratedMessage;

public class Util {

	/**
	 * protocolbuf对象转json对象
	 * 
	 * @param message
	 * @return
	 */
	public static String generatedToJson(GeneratedMessage message) {
		Gson gson = new Gson();
		String json = gson.toJson(message);
		return json;
	}
	
	/**
	 * json对象转protocolbuf对象
	 * 
	 * @param json
	 * @return
	 */
	public static GeneratedMessage jsonToGenerated(String json,GeneratedMessage message) {
		Gson gson = new Gson();
		message = gson.fromJson(json, message.getClass());
		return message;
	}
	
	/**
	 * 序列化对象转json对象
	 * 
	 * @param message
	 * @return
	 */
	public static String serialToJson(Object message) {
		Gson gson = new Gson();
		String json = gson.toJson(message);
		return json;
	}
	
	/**
	 * json转普通java可序列化对象
	 * 
	 * @param json
	 * @param message
	 * @return
	 */
	/*public static Serializable jsonToSerialObject(String json,Serializable message) {
		Gson gson = new Gson();
		message = gson.fromJson(json, message.getClass());
		return message;
	}*/
	
	/**
	 * json转普通java数组可序列化对象
	 * 
	 * @param json
	 * @param message
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static Object jsonToSerialObject(String json,Object message) {
		Gson gson = new Gson();  
		Object users = gson.fromJson(json, message.getClass());
		return users;
	}
	
	
	/**
	 * 反序列化byte【数组转对象】
	 * 
	 * @param o
	 * @return
	 */
	public static Object byteArray2Obj(byte[] data) {
		ByteArrayInputStream bin = new ByteArrayInputStream(data);
		try {
			ObjectInputStream obin = new ObjectInputStream(bin);
			Object obj = obin.readObject();
			return obj;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 序列化【对象转byte数组】
	 * 
	 * @param o必须是可序列化的对象
	 * @return 
	 */
	public static byte[] obj2ByteArray(Object o) {
		ByteArrayOutputStream obj = new ByteArrayOutputStream();
		ObjectOutputStream out;
		try {
			out = new ObjectOutputStream(obj);
			out.writeObject(o);
			return obj.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
